import React, { useEffect, useRef, useState, useLayoutEffect } from 'react';
import * as echarts from 'echarts';
import style from './styles.css';
import { LeftPage, LeftTopBox, LeftBottomBox } from './style';
import { BorderBox12, BorderBox13 } from '@jiaminghi/data-view-react';
import { ModuleTitle } from '../../style/globalStyledSet';
import * as dashboardApi from '../../services/api'; // 根据你的实际路径调整

//1-图表配置工具函数
// 1-1趋势图
const colors = [
  '#0184d5',
  '#FF9F43',
  '#27AE60',
  '#E74C3C',
  '#9B59B6',
  '#3498DB',
  '#F1C40F',
  '#1ABC9C',
  '#D35400',
  '#34495E',
];
const TREND_CHART_CONFIG = (data) => ({
  // 提示框配置
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
    textStyle: {
      fontSize: 14,
    },
    formatter: function (params) {
      let result = [
        `<div style="font-weight: bold;">${params[0].axisValue}</div>`,
      ];
      let resultSpilt = [
        `<div style="font-weight: bold; margin: 4px 0px;">---------------------------</div>`,
      ];
      params.forEach((param) => {
        if (param.value !== 0) {
          if (param.seriesName.includes('器件入库率')) {
            result.push(`
                <div>
                  <span style="color: ${param.color}">●</span>
                  ${param.seriesName}: ${(param.value * 100).toFixed(2)}%
                </div>
              `);
          }
          if (param.seriesName.includes('电路维护率')) {
            resultSpilt.push(`
                <div>
                  <span style="color: ${param.color}">●</span>
                  ${param.seriesName}: ${(param.value * 100).toFixed(2)}%
                </div>
              `);
          }
        }
      });
      if (resultSpilt.length > 1) {
        return result.join('') + resultSpilt.join('');
      } else {
        return result.join('');
      }
    },
  },
  // 图例配置 垂直滚动图例
  legend: {
    type: 'scroll',
    orient: 'horizontal',
    bottom: '5%', // 距离容器底部距离为0
    data: [
      ...data.departments.map((dept) => dept + '-器件入库率'),
      ...data.departments.map((dept) => dept + '-电路维护率'),
    ],
    textStyle: {
      // 图例文本样式配置
      color: '#FFFFFF', // 字体颜色（白色）
    },
    pageTextStyle: {
      // 分页按钮文字样式
      color: '#CCCCCC',
    },
    itemHeight: 14,
  },
  // 图表布局
  grid: {
    left: '3%',
    right: '3%',
    bottom: '20%',
    top: '3%',
    // show: true,
    borderColor: '#012f4a',
    containLabel: true,
  },
  // X轴(时间)
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: data.months,
    // interval: 0,
    axisLabel: {
      interval: 0,
      rotate: 30,
      color: 'rgba(255,255,255,.7)',
    },
    // 去除x坐标轴的颜色
    axisLine: {
      show: false,
    },
  },
  // Y轴(百分比)
  yAxis: {
    type: 'value',
    min: 0,
    max: 0.8,
    // interval: 0,
    axisLabel: {
      color: 'rgba(255,255,255,.7)',
      formatter: function (value) {
        // 更安全的百分比格式化
        return Math.round(value * 100 * 100) / 100 + '%'; // 保留两位小数
      },
    },
    // 去除刻度
    axisTick: {
      show: false,
    },

    // 修改y轴分割线的颜色
    splitLine: {
      lineStyle: {
        color: '#012f4a',
      },
    },
  },

  series: [
    ...data.departments.map((dept, index) => ({
      name: `${dept}-器件入库率`,
      type: 'line',
      itemStyle: {
        color: colors[index % colors.length],
      }, // 循环取色
      lineStyle: {
        color: colors[index % colors.length], // 设置线条颜色
        width: 2,
      },
      smooth: true,
      symbol: 'circle',
      symbolSize: 5,
      showSymbol: false,
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: colors[index % colors.length] + '80' },
          { offset: 1, color: colors[index % colors.length] + '20' },
        ]),
      },
      data: data.months.map((month) => {
        const match = data.componentStorage.find(
          (d) => d.departmentName === dept && d.month === month,
        );
        return match ? match.stockRate : 0;
      }),
    })),
    ...data.departments.map((dept, index) => ({
      name: `${dept}-电路维护率`,
      type: 'line',
      smooth: true,
      itemStyle: {
        color: colors[(index + 2) % colors.length],
      },
      lineStyle: {
        type: 'dashed',
        color: colors[(index + 2) % colors.length], // 设置虚线颜色
        width: 2,
      },
      symbol: 'circle',
      symbolSize: 5,
      showSymbol: false,
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: colors[(index + 2) % colors.length] + '80' },
          { offset: 1, color: colors[(index + 2) % colors.length] + '20' },
        ]),
      },
      data: data.months.map((month) => {
        const match = data.circuitMaintenance.find(
          (d) => d.departmentName === dept && d.month === month,
        );
        return match ? match.stockRate : 0;
      }),
    })),
  ],
});
// 1-2对比图
const COMPARE_CHART_CONFIG = (data) => ({
  // 提示框配置
  tooltip: {
    trigger: 'axis',
    formatter: function (params) {
      let result = [
        `<div style="font-weight: bold;">${params[0].axisValue}</div>`,
      ];
      let resultSpilt = [
        `<div style="font-weight: bold; margin: 4px 0px;">---------------------------</div>`,
      ];

      params.forEach((param) => {
        debugger;
        if (param.value !== 0) {
          if (param.seriesName.includes('器件入库率')) {
            result.push(`
                <div>
                  <span style="color: ${param.color}">●</span>
                  ${param.seriesName}: ${(param.value * 100).toFixed(2)}%</br>
                  已入库: ${
                    data.componentStorage[param.dataIndex].stockQuantity
                  }</br>
                  总数: ${
                    data.componentStorage[param.dataIndex].totalQuantity
                  }</br>
                </div>
              `);
          }
          if (param.seriesName.includes('电路维护率')) {
            resultSpilt.push(`
                <div>
                  <span style="color: ${param.color}">●</span>
                  ${param.seriesName}: ${(param.value * 100).toFixed(2)}%</br>
                  已维护: ${
                    data.circuitMaintenance[param.dataIndex].stockQuantity
                  }</br>
                  总数: ${
                    data.circuitMaintenance[param.dataIndex].totalQuantity
                  }</br>
                </div>
              `);
          }
        }
      });
      if (resultSpilt.length > 1) {
        return result.join('') + resultSpilt.join('');
      } else {
        return result.join('');
      }
    },
    axisPointer: {
      type: 'shadow',
    },
  },
  // 图例配置
  legend: {
    data: ['器件入库率', '电路维护率'],
    textStyle: {
      color: '#bad9ed',
    },
  },
  // 图表布局
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true,
  },
  // X轴(时间)
  xAxis: {
    type: 'category',
    data: data.departments,
    axisLabel: {
      color: '#bad9ed',
      // fontSize: 14,
      // fontWeight: 'bold',
      // fontFamily: 'Microsoft YaHei',
      interval: 0,
      rotate: 30,
    },
  },
  // Y轴(百分比)
  yAxis: {
    type: 'value',
    min: 0,
    max: 1,
    axisLabel: {
      color: '#bad9ed',
      formatter: function (value) {
        // 更安全的百分比格式化
        return Math.round(value * 100 * 100) / 100 + '%'; // 保留两位小数
      },
    },
    // 修改y轴分割线的颜色
    splitLine: {
      lineStyle: {
        color: '#012f4a',
      },
    },
  },
  // 数据系列
  series: [
    {
      name: '器件入库率',
      type: 'bar',
      data: data.componentStorage.map((item) => item.stockRate),
      itemStyle: {
        color: '#1890ff',
      },
    },
    {
      name: '电路维护率',
      type: 'bar',
      data: data.circuitMaintenance.map((item) => item.stockRate),
      itemStyle: {
        color: '#13c2c2',
      },
    },
  ],
});

//2-数据处理函数
const processChartData = (rawData) => {
  const uniqueDepts = [...new Set(rawData.map((item) => item.departmentName))];
  const uniqueMonths = [...new Set(rawData.map((item) => item.month))];

  return {
    departments: uniqueDepts,
    months: uniqueMonths,
    componentStorage: rawData.filter((r) => r.type === '器件入库率'),
    circuitMaintenance: rawData.filter((r) => r.type === '电路维护率'),
  };
};

//3-主体
const DataGovernance = () => {
  const trendChartRef = useRef(null); // 趋势图 DOM 引用
  const compareChartRef = useRef(null); // 对比图 DOM 引用
  // const [data, setData] = useState(null);
  const [compareData, setCompareData] = useState(null);
  const [trendData, setTrendData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  //3-1创建数据获取函数
  const fetchData = async () => {
    try {
      setLoading(true);

      // 并行请求数据
      const [compareResponse, trendResponse] = await Promise.all([
        dashboardApi.getBasicDataGovernanceByBuAsync(),
        dashboardApi.getBasicDataGovernanceByTrendAsync(2),
      ]);
      setCompareData(processChartData(compareResponse.data.content));
      setTrendData(processChartData(trendResponse.data.content));
    } catch (err) {
      setError(err.message || '获取数据失败');
      console.error('API调用错误:', err);
    } finally {
      setLoading(false);
    }
  };
  //在 useEffect 中调用数据获取

  useEffect(() => {
    fetchData();
    return () => {
      [trendChartRef, compareChartRef].forEach((ref) => {
        if (ref.current) echarts.dispose(ref.current);
      });
    };
  }, []);

  useLayoutEffect(() => {
    if (!compareData || !compareChartRef.current) {
      console.log('1对比图表还不能初始化，等待数据和DOM');
      return;
    }
    console.log('1对比图表开始初始化');

    // 2. 对比图
    const compareChart = echarts.init(compareChartRef.current);
    compareChart.setOption(COMPARE_CHART_CONFIG(compareData));
    window.addEventListener('resize', () => compareChart.resize());

    console.log(
      'compareData.componentStorage.map(item => item.stockRate)',
      compareData.componentStorage.map((item) => item.stockRate),
    );
    return () => {
      compareChart.dispose(); // 清理对比图实例
    };
  }, [compareData]); // 依赖 data 属性变化

  useLayoutEffect(() => {
    if (!trendData || !trendChartRef.current) {
      console.log('1趋势图表还不能初始化，等待数据和DOM');
      return;
    }
    console.log('1趋势图表开始初始化');
    // 1. 趋势图
    const trendChart = echarts.init(trendChartRef.current);
    trendChart.setOption(TREND_CHART_CONFIG(trendData));
    window.addEventListener('resize', () => trendChart.resize());

    console.log(
      '1trendData.componentStorage.map(item => item.stockRate)',
      trendData.componentStorage.map((item) => item.stockRate),
    );
    return () => {
      trendChart.dispose(); // 清理趋势图实例
    };
  }, [trendData]); // 依赖 data 属性变化

  return (
    <LeftPage>
      <ModuleTitle>
        <i className="iconfont">&#xe78f;</i>
        <span>基础数据治理</span>
      </ModuleTitle>
      <LeftTopBox>
        <BorderBox12 className="left-top-borderBox12">
          <div className="left-top">
            <ModuleTitle>
              <span>器件入库率与电路维护率 - 事业部对比</span>
            </ModuleTitle>
            <br />
            <div
              // ref={(el) => {
              //   compareChartRef.current = el;
              //   console.log('ref DOM挂载', el); // 看看它到底什么时候被挂上
              // }}
              ref={compareChartRef}
              style={{
                width: '100%',
                height: '3.35rem',
              }}
            ></div>
          </div>
        </BorderBox12>
      </LeftTopBox>

      <LeftBottomBox style={{ height: '6.75rem' }}>
        <BorderBox13 className="left-bottom-borderBox13">
          <div className="left-bottom">
            <br />
            <ModuleTitle>
              <span>器件入库率与电路维护率趋势</span>
            </ModuleTitle>
            <br />
            <div
              ref={trendChartRef}
              style={{
                width: '100%',
                height: '5rem',
              }}
            ></div>
          </div>
        </BorderBox13>
      </LeftBottomBox>
      {/* </div> */}
    </LeftPage>
  );
};

export default DataGovernance;
